package com.wecon.springdemo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Weikang  Wang
 * @program: com.wecon.springdemo.controller
 * @description:
 * @date 2020/5/5 10:11
 */
@RestController
@RequestMapping("/shiroII")
public class AuthTestController {

    private Logger logger = LoggerFactory.getLogger(AuthTestController.class);

    /**
     * 登录
     * @param name
     * @param password
     * @return
     */
    @RequestMapping(value = "/login")
    public String doLogin(@RequestParam("name") String name, @RequestParam("password") String password) {

        // 1.获取subject
        Subject subject = SecurityUtils.getSubject();
        // 2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        // 3.执行登录
        try {
            subject.login(token);
        } catch (AuthenticationException uae) {
            logger.error(uae.getMessage());
            return "Fail，认证未通过,reason:" + uae.getMessage();
        }

        if (subject.isAuthenticated()) {
            return "Success，登录认证成功，token：" + subject.getSession().getId();
        } else {
            token.clear();
            return "Fail，登录失败";
        }

    }

    @RequestMapping(value = "/add")
    public String add() {
        return "do add";
    }

    @RequestMapping(value = "/update")
    public String update() {
        return "do update";
    }

    @RequestMapping(value = "/nihao")
    public String nihao() {
        return "你好！小朋友";
    }

    @RequestMapping(value = "/everyone")
    public String everyone() {
        return "everyone 都可以直接访问";
    }

    @RequestMapping(value = "/unAuth")
    public String unAuth() {
        return "对不起，没有访问权限";
    }

}
